<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="49"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-save="false"
        :has-edit="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">关联采购订单编号:</div>
          <div class="input">
            <el-select
              v-model="searchInfo.purchaseOrderNo"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in paramNamelist"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">到货通知单号:</div>
          <div class="input">
            <el-input v-model="searchInfo.arrivalNoticeNo" clearable />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">到货日期:</div>
          <div class="input">
            <el-date-picker
              v-model="searchInfo.arrivalDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择到货日期"
              clearable
            />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">通知时间:</div>
          <div class="input">
            <el-date-picker
              v-model="searchInfo.notificationTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择到货日期"
              clearable
            />
          </div>
        </div>
        <div class="common-search-item">
          <div class="label">通知人:</div>
          <div class="input">
            <el-select
              v-model="searchInfo.Notifier"
              placeholder="请选择通知人"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in UserList"
                :key="index"
                :label="item.nickname"
                :value="item.personNo"
              />
            </el-select>
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column
          prop="purchaseOrderNo"
          label="关联采购订单编号"
          min-width="140"
        />
        <el-table-column prop="arrivalNoticeNo" label="到货通知单号" min-width="140" />
        <el-table-column prop="arrivalDate" label="到货日期" min-width="140" />
        <el-table-column prop="notificationTime" label="通知时间" min-width="80" />
        <el-table-column prop="notifierName" label="通知人" />
        <el-table-column prop="supplyProducts" label="到货图片">
          <template v-if="scope.row.pictureNoList" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="arrivalPic(scope.row.pictureNoList)"
            >查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="到货产品" width="200">
          <template v-if="scope.row.arrivalNoticeNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="arrivalseNotice(scope.row)"
            >查看产品</el-button>
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="arrivalNotice(scope.row)"
            >修改产品</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.arrivalNoticeNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(49, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(49, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '到货通知信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="采购订单编号:" prop="purchaseOrderNo" class="w50p">
            <el-select
              v-model="formData.purchaseOrderNo"
              placeholder="请选择采购订单编号"
              filterable
              @change="getCurrentMaterialValue"
            >
              <el-option
                v-for="(item, index) in paramNamelist"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="到货日期:" prop="arrivalDate" class="w50p">
            <el-date-picker
              v-model="formData.arrivalDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择到货日期"
            />
          </el-form-item>

          <el-form-item label="通知人:" prop="personNo" class="w50p">
            <el-select
              v-model="formData.personNo"
              placeholder="请选择通知人"
              filterable
            >
              <el-option
                v-for="(item, index) in UserList"
                :key="index"
                :label="item.nickname"
                :value="item.personNo"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="	通知日期:" prop="notificationTime" class="w50p">
            <el-date-picker
              v-model="formData.notificationTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择通知时间"
            />
          </el-form-item>
          <el-form-item label="到货图片:" prop="image" class="w100p">
            <ele-upload-image
              v-model="image"
              multiple
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :action="ImageUrl()"
            />
          </el-form-item>

          <el-form-item
            v-if="nowChanceStau === 'add'"
            label="到货产品 :"
            prop="product"
            class="w100p"
          >
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0 10px"></div>
            <el-checkbox-group
              v-model="checkedNos"
              @change="handlecheckedNosChange"
            >
              <el-checkbox
                v-for="(product, index) in productList"
                :key="index"
                :label="product.goodsNo"
              >{{ product.goodsName }}</el-checkbox>
            </el-checkbox-group>

            <!-- <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 0px 10px;"></div>-->
            <!-- <el-checkbox-group v-model="checkedNos" @change="handlecheckedNosChange">
              <el-checkbox v-for="item in productList" :key="item.goodsNo" :label="item.goodsName" :value="item.goodsNo">{{ item.goodsName }}</el-checkbox>
            </el-checkbox-group>-->
            <!-- <el-input v-model="formData.product" clearable /> -->
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="'到货图片'"
        :visible.sync="dialogPicFormVisible"
        width="80%"
      >
        <img style="width: 100%; height: 100%" :src="image" alt />
      </el-dialog>
      <el-dialog
        :title="'修改' + '到货产品'"
        :visible.sync="dialogNotFormVisible"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="到货产品:" prop="product" class="w100p">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0 10px"></div>
            <el-checkbox-group
              v-model="checkedNos"
              @change="handlecheckedNosChange"
            >
              <el-checkbox
                v-for="(product, index) in productList"
                :key="index"
                :label="product.goodsNo"
              >{{ product.goodsName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveAdd('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="'查看' + '到货产品'"
        :visible.sync="dialogNotceFormVisible"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="到货产品:" prop="product" class="w100p">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              disabled
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0 10px"></div>
            <el-checkbox-group
              v-model="checkedNos"
              disabled
              @change="handlecheckedNosChange"
            >
              <el-checkbox
                v-for="(product, index) in productList"
                :key="index"
                :label="product.goodsNo"
              >{{ product.goodsName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import noticeManage from "@/api/digital-operation/warehouse-inventory/arrival-notice-manage.js";
// import noticeManage from "@/api/digital-production/noticeManage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import { mapGetters } from "vuex";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "arrival-notice-manage",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    SearchBox
  },
  mixins: [mymixin],
  data() {
    return {
      searchInfo: {},
      // 采购物品
      goodsId: "",
      goodsList: [],
      // 名称
      nameList: [],
      // 选择时间
      startTime: "",
      endTime: "",
      // 日 月 周
      rulesTime: "",
      curRow: null,
      tempFormData: null,
      supplierId: "",
      paramNamelist: [],
      // 刪除的列表 唯一
      supplierIdList: [],
      rightTableData: [],
      selectedOptions: [],
      addtions: {},
      address: "",
      rules: {
        purchaseOrderNo: [
          {
            required: true,
            message: "请选择采购订单编号",
            trigger: "blur"
          }
        ],
        arrivalDate: [
          {
            required: true,
            message: "请选择到货日期",
            trigger: "blur"
          }
        ],
        personNo: [
          {
            required: true,
            message: "请选择通知人",
            trigger: "blur"
          }
        ],
        notificationTime: [
          {
            required: true,
            message: "请选择通知日期",
            trigger: "blur"
          }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
      isIndeterminate: false,
      checkedNos: [],
      productList: [],
      checkAll: true,
      pictureNoList: [],
      UserList: [],
      dialogPicFormVisible: false,
      dialogNotFormVisible: false,
      dialogNotceFormVisible: false
    };
  },
  computed: {
    headers() {
      return {
        accessToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        organizationList: sessionStorage.organizationList,
        databaseName: sessionStorage.databaseName,
        virtualSystemNo: sessionStorage.virtualSystemNo,
        sysDataBaseName: "DB_TDW1_OM1"
      };
    },
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    this.qrueyDataList();
  },
  mounted() {
    this.getTableDataList();
  },
  methods: {
    // 多选框选择方法
    handleCheckAllChange(val) {
      console.log(val);
      if (val) {
        this.checkedNos = this.productList.map(item => {
          return item.goodsName;
        });
      } else {
        this.checkedNos = [];
      }
      this.isIndeterminate = false;
    },
    handlecheckedNosChange(value) {
      console.log(value, this.checkedNos, "checkedNos");
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.productList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.productList.length;
    },
    getCurrentMaterialValue(no) {
      noticeManage
        .getCurrentMaterialValue({ purchaseOrderNo: no })
        .then(res => {
          this.productList = res.data;
        });
    },
    getTableDataList() {
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        sort: "timestamp",
        entity: {
          ppurchaseOrderNo: this.searchInfo.purchaseOrderNo,
          arrivalNoticeNo: this.searchInfo.arrivalNoticeNo,
          arrivalDate: this.searchInfo.arrivalDate,
          notificationTime: this.searchInfo.notificationTime,
          notifier: this.searchInfo.Notifier
        }
      };
      noticeManage.getArrivalNoticeList(param).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.tableData.forEach(item => {
            if (item.dizhi) {
              let site = item.dizhi.split(",", 3);
              item.site = site.join("") + item.address;
            }
          });
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async qrueyDataList() {
      const { data: res } = await noticeManage.getchaseinfo(
        sessionStorage.organizationNo
      );
      this.paramNamelist = res;
      noticeManage.getuserValue().then(res => {
        this.UserList = res.data.content;
      });
    },
    // 上传图片
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${this.$baseurl.webServiceUrl}v3/warehouse/arrivalNoticePicture/add`;
        // console.log(URL)
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    handleResponse(response, file, fileList) {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        this.$set(this.formData, "pictureNoList", [response.data]);
        noticeManage.rrivalNoticePicture(response.data).then(res => {
          this.image = "data:image/png;base64," + res.data.pictureData;
        });
        return this.image;
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    handleRemove() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        // console.log(response);
        noticeManage.delCollectionPicture(this.pictureNoList[0]).then(res => {
          if (res.code === 1) {
            delete this.pictureNoList[0];
            delete this.formData.pictureNoList[0];
            // console.log(this.formData)
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.error("点击添加/修改按钮再进行编辑!");
      }
    },
    inputChange(e) {
      const o = e.target;
      o.value = o.value.replace(/[^\u4E00-\u9FA5]/g, ""); // 清除除了中文以外的输入的字符
      this.formData.principal = o.value;
    },
    // 表格
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    add() {
      this.formData = {};
      this.openDialog("add");
    },
    cancel() {
      this.formData = {};

      this.dialogFormVisible = false;

      this.dialogPicFormVisible = false;
      this.dialogNotFormVisible = false;
    },
    arrivalNotice(e) {
      this.dialogNotFormVisible = true;
      this.formData = JSON.parse(JSON.stringify(e));
      this.checkedNos = e.goodsNoList;
      this.getCurrentMaterialValue(e.purchaseOrderNo);
    },
    arrivalseNotice(e) {
      this.dialogNotceFormVisible = true;
      this.formData = JSON.parse(JSON.stringify(e));
      this.checkedNos = e.goodsNoList;
      this.getCurrentMaterialValue(e.purchaseOrderNo);
    },
    arrivalPic(e) {
      this.dialogPicFormVisible = true;
      this.image = "";
      noticeManage.rrivalNoticePicture(e[0]).then(res => {
        this.image = "data:image/png;base64," + res.data.pictureData;
      });
    },
    handleEdit(row) {
      // console.log(row);
      // TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      this.pictureNoList[0] = row.pictureNoList[0];
      if (this.pictureNoList[0] !== undefined) {
        noticeManage.rrivalNoticePicture(row.pictureNoList[0]).then(res => {
          this.image = "data:image/png;base64," + res.data.pictureData;
        });
      } else {
        this.image = "";
      }
      this.getCurrentMaterialValue(row.purchaseOrderNo);
      // this.addActive = false;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.supplierIdList = [];
      this.supplierIdList = list.map(item => item.arrivalNoticeNo);
      if (this.supplierIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      noticeManage
        .delLisrSupplierinfo({ noList: this.supplierIdList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.getTableDataList();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
      this.resetActionBar();
    },
    handleDelete(row) {
      // noticeManage.delSupplierinfo(row.arrivalNoticeNo).then((res) => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || "删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          noticeManage.delSupplierinfo(row.arrivalNoticeNo).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    // 修改产品
    saveAdd() {
      let list = [];
      this.checkedNos.forEach(item => {
        this.productList.forEach(items => {
          // console.log(item, items)
          if (item === items.goodsNo) {
            list.push(items);
          }
        });
      });
      let param = {
        arrivalNoticeGoodsList: list,
        arrivalNoticeNo: this.formData.arrivalNoticeNo
      };
      noticeManage.arrivalNoticeGoods(param).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg || "修改成功！");
          this.dialogNotFormVisible = false;
          this.closeDialog();
          this.getTableDataList();
        } else {
          this.$message.error(res.msg || "修改失败！");
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            noticeManage.editSupplierinfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.selectedOptions = [];
                this.address = "";
                this.$refs[formData].resetFields();
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let list = [];
            this.checkedNos.forEach(item => {
              this.productList.forEach(items => {
                // console.log(item, items)
                if (item === items.goodsNo) {
                  list.push(items);
                }
              });
            });
            this.formData.arrivalNoticeGoodsList = list;
            // console.log(this.formData)
            // return
            noticeManage.addSupplierinfo(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.selectedOptions = [];
                this.address = "";
                this.$refs[formData].resetFields();
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.search-item {
  display: flex;
  height: 36px;
  margin-left: 20px;
  white-space: nowrap;
  &:first-child {
    margin: 0;
  }
  span {
    display: inline-block;
  }
  &.rules-wrap span {
    padding: 0 15px;
    border: 1px solid $borderColor;
    cursor: pointer;
    transition: border-color 0.2s;
    box-sizing: border-box;
    &:hover {
      border-color: #6ecae3;
    }
  }
}
.el-date-editor,
.el-select {
  width: 100%;
}

::v-deep .el-form {
  .el-form-item__label {
    min-width: 120px !important;
  }
}
h4.total-price {
  display: flex;
  justify-content: space-between;
  margin: 0;
}

.right-table {
  line-height: 0px;
}

::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}
::v-deep .el-upload--picture-card {
  position: relative;
}
::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
// 地址
.adress {
  ::v-deep .el-form-item__content {
    flex-wrap: wrap;
    .el-cascader {
      font-size: 10px;
      // height: 20px;
      // line-height: 22px;
      width: 100%;
      .el-input__inner {
        font-size: 10px;
        height: 30px;
        line-height: 30px;
      }
    }
  }
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    .el-dialog__body {
      overflow-y: auto;
    }
  }
}
</style>
